drop table test_cube;
drop table test_bktree;
drop table test_vector;
drop extension cube;
drop extension bktree;
drop extension vector;

CREATE OR REPLACE FUNCTION create_index(tablename varchar, clomnname varchar) RETURNS void AS $$
DECLARE
m integer;
total integer;
b integer;
mplus integer;
dim integer;
histgramrate integer;
samplearray int8[];
hist integer[];
statistics_array integer[];
BEGIN

SELECT get_m() INTO m;
EXECUTE format('SELECT get_hmcode_dim(%s) from %s limit 1',clomnname,tablename) INTO dim;
SELECT ceil(dim::float4/m) INTO b;
SELECT get_histgramrate() INTO histgramrate;


RAISE NOTICE 'dim = %',dim;
RAISE NOTICE 'm = %',m;
RAISE NOTICE 'b = %',b;

EXECUTE format('CREATE TABLE temp AS SELECT id, hmcode_split(%s,%s) as arr FROM %s', clomnname, m, tablename);
EXECUTE format('CREATE TABLE sampletable AS SELECT * FROM temp WHERE id %% %s = 1',histgramrate);

FOR i IN 1..m LOOP
	EXECUTE format('CREATE TABLE hm_index%s (id int4 REFERENCES %s(id), code uint4)',i,tablename);
	EXECUTE format('INSERT INTO hm_index%s SELECT id,arr[%s]::uint4 from temp', i, i);
	EXECUTE format('CREATE INDEX ON hm_index%s using hash(code)',i);
	SELECT array_agg(arr[i]::int8) FROM sampletable INTO samplearray;
	-- FOR I IN array_lower(samplearray, 1)..array_upper(samplearray, 1) LOOP
	-- 	RAISE NOTICE '%',samplearray[I];
	-- END LOOP;
	SELECT get_statistics_array(samplearray, dim, m) INTO statistics_array;
	hist = array_cat(hist,statistics_array);
END LOOP;
-- RAISE NOTICE '%',array_upper(hist,1);
-- FOR I IN array_lower(hist, 1)..array_upper(hist, 1) LOOP
-- 	RAISE NOTICE '%',hist[I];
-- END LOOP;
CREATE TABLE hist AS SELECT hist;
EXECUTE format('SELECT count(*) FROM %s',tablename) INTO total;
EXECUTE format('SELECT set_total(%s)',total);
-- $1 can make it still string
-- EXECUTE format('SELECT create_trigger($1,$2)')using tablename,clomnname;
DROP TABLE temp;
DROP TABLE sampletable;
END
$$
LANGUAGE plpgsql;
